﻿package com._public._ui
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import flash.events.Event;
	/**
	 * 色彩选取组件
	 * @author WZH(shch8.com)
	 * 一：使用方法：
		1.直接使用，自动创建触发按钮
			col = new ColorSel()
			col.colMark="#"
			addChild(col)
			col.x = col.y = 200
		2。自定义触发按钮,须要设置触发按钮与彩色改变时自动着色的对象即new ColorSel(按钮,着色对象)
			如果没有设定第二个着色对象参数，默认对按钮进行着色
			var mc1:Sprite;//当作色彩按钮
			var mcCol:Sprite;//当作色彩指示器，可以不使用
			new ColorSel(mc,mcCol)
			
		二：选中颜色后，回调方式获取
		col.callChange = function(color:String) {
				trace(color)
				}
		三：获取与设置
		col.useColorMore=false;//设置是否使用更多颜色
		col.colorStr;//获取当前选中的颜色字符串
		col.color;//获取当前选中的颜色数字
		col.colMark="#";设置颜色字符前缀，如#00ffcc中0x00ffcc方式
		show();//显示色彩选取面板
		hide();//显示色彩选取面板
	 *
	 */
	public class ColorSel extends Sprite
	{
		 public var colorArr:Array = [
			["ff","ff", "dd", "aa", "88", "66"],
			["00", "b0", "90", "60", "30", "0"],
			["dc163c", "f9b0be", "f6778f", "cc3300", "b20022", "6d0015"],//红色
			["ff6600", "fdcba8", "dcba84", "e88101", "a4522c", "6d3319"],//橙色
			["b5b601", "f8f824", "ffff00", "c5c501", "a0a000", "7e7e00"],//黄色
			["008800", "64ceac",  "04fe04", "3cb274", "117903", "045225"],//绿色
			["0402fc", "84cefc", "6496ec", "446ae4", "0f42a1", "040284"],//蓝色
			["048a8c", "4cd2cc", "24b2ac", "03a4a9", "027579", "075456"],//青色
			["840284", "dc72d4", "d834cc", "9402d4","8c2ae4","4c0284"],//紫色
			]
	
		private var _target:Sprite;
		private var _colShim:Sprite;
		private var colArea:ColorFormArea;
		/**
		 * 设置弹出时显示位置，不设置将使用舞台鼠标坐标
		 */
		public var setPoint:Point;
        private var lastestColor:String = "000000";//最近的一次颜色值
		private var _color:uint
		private var _stage:Stage
		private const NAME:String = "colorSel_ColorFormArea"
		private var _useColorMore:Boolean=true;
		/**
		 * 色彩标识
		 */
		public var colMark:String = "0x";
		public var callChange:Function;
		private var defaultValue:uint;//默认值
		/**
		 * @param	colShim 色彩要被改变的对象
		 * @param	target  事件感应的对象
		 */
		public function ColorSel(colShim:Sprite = null, target:Sprite = null)
		{
			if (colShim == null) {
				_target = new Clicker;
				_colShim = _target.getChildByName("colorTag") as Sprite;
				addChild(_target);
				}else {
					_colShim = colShim
					_target = target == null?colShim:target;
				}
			_target.addEventListener(MouseEvent.CLICK, tarClickEvent)
			_stage = _target.stage;
			if(_stage==null)
			_target.addEventListener(Event.ADDED_TO_STAGE,stageInit)
		}
		private function stageInit(e:Event):void {
			_target.removeEventListener(Event.ADDED_TO_STAGE,stageInit)
			_stage = _target.stage;
		}
		/**
		 * 设置默认值
		 * @param	v
		 */
		public function setDefault(v:uint):void {
			defaultValue = color = v;
		}
		/**
		 * 恢复成默认值
		 */
		public function reDefault():void {
			color = defaultValue;
		}
		/**
		 * 使用更多颜色
		 */
		public function set useColorMore(value:Boolean):void {
			_useColorMore = value;
		}
		/**
		 * 获取颜色字符串
		 */
		public function get colorStr():String {
            return colMark+lastestColor;
        }
		 /**
         * 获得颜色值
         */
        public function get color():uint {
            return uint("0x"+lastestColor);
        }
        public function set color(value:uint):void{
            lastestColor = value.toString(16);
			setShimCol(false);
        }
		/**
		 * 修改了颜色表以后，刷新色彩列表
		 */
		public function refreshColor():void {
			colArea=_stage.getChildByName(NAME) as ColorFormArea;
			if (colArea != null) {
				colArea.parent.removeChild(colArea)
				colArea = null;
				}
			createColArea();
			hide();
		}
		private function txtEnter(e:KeyboardEvent):void {
			if (e.keyCode == 13) clickThis();
		}
		//创建或获取舞台上的colArea
		private function createColArea():void {
			if (colArea == null) {
				colArea=_stage.getChildByName(NAME) as ColorFormArea;
				if (colArea == null) colArea = new ColorFormArea(colorArr);
				colArea.name = NAME;
				_stage.addChild(colArea)
			}else if(colArea.stage==null){
				colArea = null;
				createColArea();
				}
		}
		//设置目标对象的颜色
		private function setShimCol(seting:Boolean=true):void {
			var colForm:ColorTransform = new ColorTransform;
			colForm.color = color;
			_colShim.transform.colorTransform = colForm;
			if (!seting) return;
			if(colArea!=null)colArea.cache("0x"+lastestColor);
			if (callChange is Function) callChange(color);
			this.dispatchEvent(new Event(Event.CHANGE));
		}
		//点击
		private function clickThis(event:MouseEvent = null):void {
			if(event!=null)
			if (!(event.target is ColorForm) && colArea.hitTestPoint(_stage.mouseX, _stage.mouseY)&&event.target.name!="col") return;
			if (colArea.visible) {
				_stage.removeEventListener(MouseEvent.MOUSE_DOWN, clickThis);
				colArea.txt.removeEventListener(KeyboardEvent.KEY_DOWN,txtEnter)
				colArea.visible = false;
				setShimCol();
			}
		}
		private function tarClickEvent(e:MouseEvent):void {
			show()
		}
		/**
		 * 隐藏色彩面板
		 */
		public function hide():void {
			colArea.visible = false;
		}
		/**
		 * 显示色彩面板
		 */
		public function show():void {
			createColArea();
			colArea.colMark = colMark;
			colArea.useColorMore = _useColorMore
			colArea.colorStr = colorStr
			var point:Point = new Point(_target.x, _target.y);
			point = _target.parent.localToGlobal(point);
			if ((point.x + colArea.width) > _stage.stageWidth) {
				colArea.x = _stage.stageWidth - colArea.width;
				}else {
					colArea.x = point.x;
					}
			if ((point.y + colArea.height) > _stage.stageHeight) {
				colArea.y =point.y-colArea.height;
				}else{
				colArea.y = point.y + _target.height;
				}
			colArea.theHandler = function(col:String):void {
					lastestColor = col;//滑过时选中的
				}
			colArea.visible = true;
			_stage.addEventListener(MouseEvent.MOUSE_DOWN, clickThis);
			colArea.txt.addEventListener(KeyboardEvent.KEY_DOWN,txtEnter)
		}
		
		override public function get width():Number { return _target.width; }
		
		override public function set width(value:Number):void
		{
			_target.width = value;
		}
		override public function get height():Number { return _target.height; }
		
		override public function set height(value:Number):void
		{
			_target.height = value;
		}
	}
}

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.GradientType;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
import flash.geom.Matrix;
import flash.net.SharedObject;
import flash.text.TextField;
import flash.text.TextFieldType;
//色彩表
class ColorFormArea extends Sprite {
	
    private var colorArr:Array;
	
	private var cacheArr:Array = [];//缓存数据
	
    public var txt:TextField = new TextField;
    /**
     * 颜色改变时的处理函数
     */
    public var theHandler:Function;
	public var ellpse:uint = 8;//绘制的圆角

    /**
     * 颜色块区域
     */
    private var colorRects:Sprite = new Sprite;
	private const DIS:uint = 1;//间距
	private var colBox:Sprite;//色盘选取器
	private var colBoxBtn:Sprite;
	private var colBoxBitmap:BitmapData;
	private var colTip:Shape
	private var setX:uint=7;
	private var setY:uint = 5
	private var selCol:String="000000";//选中的色值，不加标识
    private var latestColorForm:ColorForm;//最近一次选中的方块
	
	public var colMark:String = "#";//色彩标识
	
    /**
     * 构造一个新的ColorFormArea实例
     */
    public function ColorFormArea(colArr:Array):void {
		colorArr=colArr
        var wid:Number=(colWid+DIS)*colorArr.length+15
		var hei:Number = (colWid + DIS) * colLen+colWid+DIS*2 + 40
        var bg:Sprite = new Sprite;
		
        with(bg){
            graphics.beginFill(0xf6f6f6);
			graphics.lineStyle(1,0xbbbbbb,1,true)
            graphics.drawRoundRect(0, 0, wid, hei,ellpse,ellpse);
            graphics.endFill();
			graphics.lineStyle(1,0xffffff,1,true)//画内白线
            graphics.drawRoundRect(1,1, wid-2, hei-2,ellpse,ellpse);
            graphics.endFill();
        }
        //添加滤镜
        addChild(bg);

        txt.width = 60;
        txt.height = 20;
		bg.graphics.lineStyle(1, 0xdddddd,1,true);//绘制文本框背景
		bg.graphics.beginFill(0xffffff);
		bg.graphics.drawRoundRect(5, 5, 70, 20,ellpse,ellpse)
		bg.graphics.endFill()
        txt.type = TextFieldType.INPUT;
        txt.x =setX+18;
        txt.y = setY;
        txt.maxChars = 7;
        txt.restrict = "0-9a-f#";
        txt.addEventListener(Event.CHANGE, txtChange);
        addChild(txt);
		colTip = new Shape;
		colTip.x = setX;
		colTip.y = setY;
		addChild(colTip)
		colorStr = "000000"
		
        colorRects.x = setX + 1;
        colorRects.y = setY + txt.height + 5;
        addChild(colorRects);
		var len1:uint=colorArr.length;
		var len2:uint = colLen;
		var colStr:String
		var colorForm:ColorForm
        for (var i:int = 0; i < len1; i++) {
            for (var j:int = 0; j < len2; j++) {
				colStr = colorArr[i][j];
				if(colStr.length==2)colStr=colStr+colStr+colStr
                colorForm = new ColorForm("0x"+colStr, selectColorHandler);
                colorForm.x = i * (colWid+DIS);
                colorForm.y = j * (colWid + DIS);
				if (j >= 1) {
					colorForm.y += 3;
				}
                colorRects.addChild(colorForm);
            }
        }
        this.addEventListener(Event.REMOVED_FROM_STAGE, removeThis);
	}
	public function set useColorMore(value:Boolean):void {
		if(colBoxBtn==null&&value){
		colBoxBtn = new Sprite;//创建按钮
		colBoxBtn.addChild(createColBox("btn",16,16))
		colBoxBtn.graphics.lineStyle(1, 0xffffff);
		colBoxBtn.graphics.beginFill(0x993333)
        colBoxBtn.graphics.drawCircle(8, 8, 6);
		colBoxBtn.graphics.endFill();
		colBoxBtn.buttonMode = true;
		addChild(colBoxBtn);
		colBoxBtn.x = 80;
		colBoxBtn.y = txt.y+1;
		colBoxBtn.addEventListener(MouseEvent.CLICK, colBoxEvent);
		colBoxBtn.addEventListener(MouseEvent.MOUSE_OVER,colBoxEvent)
		colBoxBtn.addEventListener(MouseEvent.MOUSE_OUT, colBoxEvent)
		}
		if (colBoxBtn == null) return;
		colBoxBtn.visible = value;
		if (!value && colBox != null) setColMoreBorder(false);
	}
	public function set colorStr(value:String):void {
		selCol = (value.indexOf(colMark) != -1)?value.slice(colMark.length,value.length):value;
		 if(txt.text!=value)txt.text = colMark + selCol;
		 colTip.graphics.clear();
		 colTip.graphics.beginFill(uint("0x" + selCol));
		 colTip.graphics.drawRoundRect(0, 2, 16, 17, ellpse);
		 colTip.graphics.endFill();
	}
	/**
	 * 创建色组
	 * @return
	 */
	private function createColBox(boxName:String="",wid:int=-1,hei:int=-1):Sprite {
		var colBox:Sprite = new Sprite
		addChild(colBox)
		if (boxName != "") colBox.name = boxName;
		var myMatrix:Matrix = new Matrix();
        myMatrix.createGradientBox(200, 200, 0, 0, 0);

         var colors:Array = [0xff0000,0xffff00,0x00ff00,0x0000ff,0xff00ff,0xff0000];
         var alphas:Array = [100,100,100,100,100,100];
             var ratios:Array = [0, 0x44, 0x77, 0x99, 0xcc, 0xFF];
             colBox.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios,myMatrix);
             colBox.graphics.drawRoundRect(0, 0, 200, 200,ellpse*3);
			
			 myMatrix.rotate(Math.PI/2);
			 colors = [0xffffff,0xffffff,0];
             alphas = [100,0,100];
             ratios = [0,0x77,0xf8];
             colBox.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios,myMatrix);
             colBox.graphics.drawRoundRect(0, 0, 200, 200, ellpse*3);
			 if (wid != -1) colBox.width = wid;
			 if (hei != -1) colBox.height = hei;
			return colBox;
	}
	override public function set visible(value:Boolean):void
	{
		super.visible = value;
		if (value) {
			colorStr = selCol;
			drawCache();
			}
	}
	//生成缓存色块
	private function drawCache():void {
		var colorForm:ColorForm
		if (cacheArr.length == 0)cache();
		var len:uint = cacheArr.length;
		if (len > cacheArr.length) len = cacheArr.length - 1;
		for (var i:uint=0; i<len;i++ ) {
			colorForm = colorRects.getChildByName("c" + i) as ColorForm;
			if (colorForm == null) {
				colorForm = new ColorForm(cacheArr[i],selectColorHandler)
				colorRects.name = "c" + i;
				colorForm.x = (len-i-1) * (colWid + DIS)
				colorForm.y = (colLen + DIS) * colWid;
				colorRects.addChild(colorForm)
				}else {
					colorForm.color=cacheArr[i]
					}
			}
	}
	private function get colWid():uint { return ColorForm.colorWid * 2 };
	private function get colLen():uint {
		return colorArr[0].length
	}
	/**
	 * 选中颜色加入缓存，无参数表示取数据
	 * @param	saveCol
	 * @return
	 */
	public function cache(saveCol:String=""):Array
	{
		var mySo:SharedObject = SharedObject.getLocal("ColorSelCache");
		
		cacheArr = mySo.data.colArr
		if (cacheArr == null) cacheArr = [];
		if (saveCol != "") {
			for (var i:uint; i < cacheArr.length; i++ ) {
				if (cacheArr[i] == saveCol) {
					cacheArr.splice(i, 1);
					}
			}
			if (cacheArr.length >= colorArr.length) {
				cacheArr.shift();
				if (cacheArr.length > colorArr.length) cacheArr = [];
				}
			cacheArr.push(saveCol)
			mySo.data.colArr=cacheArr;
			mySo.flush();
		}else {
			cacheArr = mySo.data.colArr
			if (cacheArr == null) cacheArr = [];
			}
		return cacheArr;
	}
	//设置是否显示更多颜色
	private function setColMoreBorder(value:Boolean):void {
		if(value){
			colBox.visible = true;
			colBoxBtn.getChildByName("btn").visible = false;
			}else {
				colBoxBtn.getChildByName("btn").visible = true;
				colBox.visible = false;
				}
	}
	//色盘移动
	private function colPickMove(e:MouseEvent):void
	{
		if (colBox.mouseX >= colBox.width || colBox.mouseY >= colBox.height) return;
		colorStr = colBoxBitmap.getPixel(colBox.mouseX, colBox.mouseY).toString(16);
	}
	//色盘拾取
	private function colPickClick(e:MouseEvent):void
	{
		callHandler(colBoxBitmap.getPixel(colBox.mouseX, colBox.mouseY).toString(16));
	}
	//色盘模式切换按钮事件
	private function colBoxEvent(e:MouseEvent):void {
		switch(e.type) {
			case MouseEvent.MOUSE_OVER:
			colBoxBtn.y-=0.5
			break
			case MouseEvent.MOUSE_OUT:
			colBoxBtn.y+=0.5
			break
			case MouseEvent.CLICK:
			if (colBox == null) {
				colBox = new Sprite()
				colBox.addChild(createColBox("col",colorRects.width+2,colorRects.height-15));
				colBox.addEventListener(MouseEvent.MOUSE_MOVE, colPickMove);
				colBox.addEventListener(MouseEvent.MOUSE_DOWN, colPickClick);
				addChild(colBox);
				colBox.x = colorRects.x-2;
				colBox.y = colorRects.y-1;
				colBoxBitmap = new BitmapData(colBox.width, colBox.height);
				colBoxBitmap.draw(colBox);
				colBox.visible = false;
				}
			setColMoreBorder(!colBox.visible)
			break
			}
	}
    /**
     * 移除侦听器
     * @param    event
     */
    private function removeThis(event:Event):void {
        if(txt!=null)txt.removeEventListener(Event.CHANGE, txtChange);
        this.removeEventListener(Event.REMOVED_FROM_STAGE, removeThis);
		if(colBoxBtn!=null){
		colBoxBtn.removeEventListener(MouseEvent.CLICK, colBoxEvent)
		colBoxBtn.removeEventListener(MouseEvent.MOUSE_OVER,colBoxEvent)
		colBoxBtn.removeEventListener(MouseEvent.MOUSE_OUT, colBoxEvent)
		}
		if(colBox!=null){
		colBox.removeEventListener(MouseEvent.MOUSE_MOVE, colPickMove);
		colBox.removeEventListener(MouseEvent.MOUSE_DOWN, colPickClick);
		}
    }

    private function selectColorHandler(color:String, colorFrom:ColorForm):void {
		selCol = color;
		colorStr = isJtag(color)?color.slice(2, 8):color;
        txtChange(colorFrom);
    }
	private function isJtag(value:String):Boolean {
		return value.slice(0, 1)=="#";
	}

	//选中后刷新显示，或文本框加改变刷新
    private function txtChange(event:Object = null):void {
		colorStr = txt.text
		callHandler(selCol)
		if (latestColorForm) latestColorForm.select = false;
		var colorForm:ColorForm =event as ColorForm
        if (colorForm) {
			colorForm.select = true;
			latestColorForm = colorForm;
			return
			}
    }

    /**
     * 颜色改变时调用此函数
     * @param    color
     */
    private function callHandler(color:String):void {
		selCol = color
        if (theHandler is Function) {
            theHandler(color);
        }
    }
}

class ColorForm extends Sprite {

    private var theHandler:Function;

    /**
     * 颜色块的颜色
     */
    private var theColor:String = "";

    private var sharp:Shape = new Shape;//选中图形
    public static var colorWid:uint = 6;
    /**
     * 颜色块
     * @param    color
     * @param    mouseOverHandler
     */
    public function ColorForm(_color:String, mouseOverHandler:Function = null):void {
        theHandler = mouseOverHandler;
		color = _color;
        sharp.graphics.lineStyle(1, 0x333333);
        sharp.graphics.drawCircle(colorWid, colorWid, colorWid);
        addChild(sharp);
        sharp.visible = false;

        this.addEventListener(Event.REMOVED_FROM_STAGE, removeThis);
        this.addEventListener(MouseEvent.MOUSE_OVER, mouseOverThis);
    }

    private function mouseOverThis(event:MouseEvent):void {
        if (Boolean(theHandler)) {
            theHandler(theColor.slice(2,8),this);
        }
    }

    private function mouseOutThis(event:MouseEvent):void {
        select = false;
    }

    private function removeThis(event:Event):void {
        this.removeEventListener(Event.REMOVED_FROM_STAGE, removeThis);
        this.removeEventListener(MouseEvent.MOUSE_OVER, mouseOverThis);
    }

    /**
     * 获得或设置选中状态
     */
    public function set select(value:Boolean):void {
        sharp.visible = value;
    }
    public function get select():Boolean {
        return sharp.visible;
    }

    /**
     * 获得本色块的颜色
     */
    public function get color():String {
        return theColor;
    }
	 public function set color(value:String):void {
        if (theColor == value) return;
		theColor = value
		graphics.clear();
		graphics.lineStyle(1,0xaaaaaa);
        graphics.beginFill(uint(value));
        graphics.drawCircle(colorWid, colorWid, colorWid);
        graphics.endFill();
    }
}


import flash.display.CapsStyle;
import flash.display.JointStyle;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.BevelFilter;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.text.TextField;
import flash.text.TextFieldType;
class Clicker extends Sprite {

    /**
     * 拾色器的头
     */
    private var myColorArea:Sprite;
	private var blackArr:Shape
    /**
     * 包含的颜色的字符串表示形式
     */
    private var theColor:String = "0x000000";
	private var wid:uint = 20;
	private var hei:uint = 20;
    public function Clicker():void {

		myColorArea = new Sprite;
		changeColArea(0);
        myColorArea.x = 2.5;
        myColorArea.y = 2.5;
		myColorArea.name="colorTag"
        addChild(myColorArea);

        blackArr= new Shape;
        blackArr.graphics.beginFill(0xEEEEEE);
        blackArr.graphics.drawRect(0, 0, 8, 6);
        blackArr.graphics.endFill();
        blackArr.graphics.beginFill(0);
        blackArr.graphics.lineStyle(.01, 0xCCCCCC, 1, true, "normal", CapsStyle.SQUARE, JointStyle.MITER);
        blackArr.graphics.moveTo(1, 1);
        blackArr.graphics.lineTo(7, 1);
        blackArr.graphics.lineTo(4, 5);
        blackArr.graphics.lineTo(1, 1);
        blackArr.graphics.endFill();
        addChild(blackArr);
		drawBorder();
    }
	private function changeColArea(color:uint):void {
		myColorArea.graphics.clear();
        myColorArea.graphics.beginFill(color);
        myColorArea.graphics.drawRect(0, 0,  wid-5,  hei-5);
        myColorArea.graphics.endFill();
	}
    /**
     * 改变选中的颜色
     * @param    color
     */
    public function changeColor(color:uint):void {
        changeColArea(color);
    }

    /**
     * 设置颜色
     */
    public function set color(color:String):void {
        theColor = color;
        changeColArea(uint(color));
    }
    /**
     * 获得颜色
     */
    public function get color():String {
        return theColor;
    }
	override public function get width():Number { return wid; }
	
	override public function set width(value:Number):void
	{
		wid = value;
		drawBorder()
	}
	override public function get height():Number { return hei; }
	
	override public function set height(value:Number):void
	{
		hei = value;
		drawBorder()
	}
	private function drawBorder():void {
		with (graphics) {
			clear()
            lineStyle(1, 0xFFFFFF, 1, true, "normal",CapsStyle.SQUARE, JointStyle.MITER);
            moveTo(0, hei);
            lineTo(0, 0);
            lineTo(wid, 0);
            lineStyle(1, 0xAAAAAA, 1, true, "normal", CapsStyle.SQUARE, JointStyle.MITER);
            lineTo(wid, hei);
            lineTo(0, hei);
            lineStyle(1, 0xEEEEEE, 1, true, "normal", CapsStyle.SQUARE, JointStyle.MITER);
            moveTo(1, hei-1);
            lineTo(1, 1);
            lineTo(wid-1, 1);
            lineTo(wid-1, hei-1);
            lineTo(1, hei-1);
            lineStyle(1, 0xCCCCCC, 1, true, "normal", CapsStyle.SQUARE, JointStyle.MITER);
            moveTo(2, hei-2);
            lineTo(2, 2);
            lineTo(wid-2, 2);
            lineStyle(1, 0xFFFFFF, 1, true, "normal", CapsStyle.SQUARE, JointStyle.MITER);
            lineTo(wid-2, hei-2);
            lineTo(2, hei-2);
        }
		blackArr.x = this.width - blackArr.width - 2;
        blackArr.y = this.height - blackArr.height - 2;
		color = theColor;
	}
}
